package com.grace.cms.search.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import com.grace.common.core.controller.BaseController;
import com.grace.common.core.domain.AjaxResult;
import com.grace.cms.search.lucene.document.ArticleDocument;
import com.grace.cms.search.lucene.document.CategoryDocument;
import com.grace.cms.search.lucene.document.TagDocument;
import com.grace.cms.search.lucene.document.SearchableDocument;
import com.grace.cms.search.lucene.service.LuceneSearchService;
import java.io.IOException;
import java.util.List;

/**
 * 搜索控制器
 */
@RestController
@RequestMapping("/search")
public class SearchController extends BaseController {
    
    @Autowired
    private LuceneSearchService luceneSearchService;
    
    /**
     * 添加文章文档
     * @param document 文档
     * @return 结果
     */
    @PostMapping("/document/article")
    public String addArticleDocument(@RequestBody ArticleDocument document) {
        try {
            luceneSearchService.addDocument(document);
            return "Article document added successfully";
        } catch (IOException e) {
            return "Error adding document: " + e.getMessage();
        }
    }
    
    /**
     * 添加分类文档
     * @param document 文档
     * @return 结果
     */
    @PostMapping("/document/category")
    public String addCategoryDocument(@RequestBody CategoryDocument document) {
        try {
            luceneSearchService.addDocument(document);
            return "Category document added successfully";
        } catch (IOException e) {
            return "Error adding document: " + e.getMessage();
        }
    }
    
    /**
     * 添加标签文档
     * @param document 文档
     * @return 结果
     */
    @PostMapping("/document/tag")
    public String addTagDocument(@RequestBody TagDocument document) {
        try {
            luceneSearchService.addDocument(document);
            return "Tag document added successfully";
        } catch (IOException e) {
            return "Error adding document: " + e.getMessage();
        }
    }
    
    /**
     * 搜索文档
     * @param query 查询字符串
     * @return 搜索结果
     */
    @GetMapping("/query")
    public AjaxResult search(@RequestParam("query") String query) {
        try {
            return success(luceneSearchService.search(query, 10));
        } catch (Exception e) {
            throw new RuntimeException("Search failed: " + e.getMessage(), e);
        }
    }
    
    /**
     * 根据类型搜索文档
     * @param query 查询字符串
     * @param type 文档类型 (article, category, tag)
     * @return 搜索结果
     */
    @GetMapping("/query/{type}")
    public List<SearchableDocument> searchByType(@RequestParam("query") String query, @PathVariable("type") String type) {
        try {
            return luceneSearchService.searchByType(query, type, 10);
        } catch (Exception e) {
            throw new RuntimeException("Search failed: " + e.getMessage(), e);
        }
    }
}